package com.web.observers;

import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.function.Supplier;

/**
 * @Author: wws
 * describe:
 */
public class RequestResultObserver implements Observer, Supplier<byte[]> {

    private byte[] data;
    private Observable observable;
    private byte[] frame;

    public RequestResultObserver(byte[] frame) {
        this.frame = frame;
    }

    @Override
    public void update(Observable o, Object arg) {
        this.observable = o;
        this.data = (byte[]) arg;

        synchronized (this) {
            notify();
            observable.deleteObserver(this);
        }

    }

    @Override
    public byte[] get() {
        System.out.println("等待接收数据。。。。。。。。");
        for (; ; ) {
            System.out.println("开始循环");

            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


            if (data == null && data.length < 5) {
                continue;
            }
            System.out.println("shoudaoshuju1111" + Arrays.toString(data));
            if (Arrays.equals(frame, Arrays.copyOfRange(data, 1, 3))) {
                observable.deleteObserver(this);
                System.out.println("shoudaoshuju22222" + Arrays.toString(data));

                return data;
            }
        }
    }


}
